package statistic;

import database.DatabaseHelper;
import entity.Student;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class StudentGPAList {

    public ArrayList<Student> students = new ArrayList<>();
    public ArrayList<Double> GPA = new ArrayList<>();
    public int pageSize = 0;
    public int pageIdx = 0;
    public int stuTotal = 0;
    public int pageTotal = 0;

    public enum Aggregate {

        TOTAL, AVERAGE;

        @Override
        public String toString() {
            switch (this) {
                case TOTAL:
                    return "sum(score.total)";
                case AVERAGE:
                default:
                    return "avg(score.total)";
            }
        }

    }

    public enum Order {

        ID, GPA;

        @Override
        public String toString() {
            switch (this) {
                case ID:
                    return "stu_id";
                case GPA:
                default:
                    return "GPA DESC";
            }
        }

    }

    public StudentGPAList(Aggregate aggFunc, Order order, int pageIdx, int pageSize) throws SQLException {
        this.pageIdx = pageIdx;
        this.pageSize = pageSize;
        String query = String.format("select %s as GPA,stu_id from score group by stu_id order by %s LIMIT ?, ?", aggFunc, order);
        DatabaseHelper db = new DatabaseHelper();
        ResultSet rs = db.query(query, pageIdx * pageSize, pageSize);
        while (rs.next()) {
            GPA.add(rs.getDouble(1));
            students.add(Student.find(db, rs.getString(2)));
        }
        rs.close();
        ResultSet rs2 = db.query("select count(distinct(stu_id)) from score");
        if (rs2.next()) {
            stuTotal = rs2.getInt(1);
            pageTotal = (int)Math.ceil((double)stuTotal / (double) pageSize);
        }
        rs2.close();
        db.close();
    }

}
